package com.zhuiyun.educations.api.voidea.controller;

import com.zhuiyun.educations.api.voidea.entity.FileChunkDTO;
import com.zhuiyun.educations.api.voidea.entity.FileChunkResultDTO;
import com.zhuiyun.educations.api.voidea.entity.RestApiResponse;
import com.zhuiyun.educations.api.voidea.service.VoideaaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @ClassName VoideaController
 * @Description TODO
 * @Author yuanb
 * @Date 2023/7/23 18:45
 **/
@RestController
@RequestMapping("upload")
@Slf4j
@CrossOrigin
public class VoideaController {
    @Autowired
    private VoideaaService voideaaService;
    /**
     * 检查分片是否存在
     *
     * @return
     */
    @GetMapping("chunk")
    public RestApiResponse<Object> checkChunkExist(FileChunkDTO chunkDTO) {
        FileChunkResultDTO fileChunkCheckDTO;
        try {
            fileChunkCheckDTO = voideaaService.checkChunkExist(chunkDTO);
            return RestApiResponse.success(fileChunkCheckDTO);
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }


    /**
     * 上传文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("chunk")
    public RestApiResponse<Object> uploadChunk(FileChunkDTO chunkDTO) {
        try {
            System.out.printf("当前序号=================="+chunkDTO.getChunkNumber());
            voideaaService.uploadChunk(chunkDTO);
            return RestApiResponse.success(chunkDTO.getIdentifier());
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }

    /**
     * 请求合并文件分片
     *
     * @param chunkDTO
     * @return
     */
    @PostMapping("merge")
    public RestApiResponse<Object> mergeChunks(@RequestBody FileChunkDTO chunkDTO) {
        try {
            boolean success = voideaaService.mergeChunk(chunkDTO.getIdentifier(), chunkDTO.getFilename(), chunkDTO.getTotalChunks());
            return RestApiResponse.flag(success);
        } catch (Exception e) {
            return RestApiResponse.error(e.getMessage());
        }
    }
}
